<template>
  <div class="upload-container">
    <div class="upload-content">
      <el-upload
        :class="isUpload ? 'UploadSuccess' : 'BeforeUpload'"
        ref="upload"
        :action="uploadUrl"
        :headers="headers"
        :on-success="handleSuccess"
        :on-error="handleError"
        :multiple="false"
        drag
        :before-upload="beforeUpload"
        :limit="1"
        :file-list="fileList"
        :on-remove="handleRemove"
      >
        <svg
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          width="20px"
          height="20px"
          style="margin:0 auto;color:#82827e"
          focusable="false"
          aria-hidden="true"
        >
          <path
            fill-rule="evenodd"
            clip-rule="evenodd"
            d="M17.8395 8.05827C17.1837 5.16226 14.5944 3 11.5 3C7.91015 3 5 5.91015 5 9.5C5 10.0204 5.06115 10.5264 5.17665 11.0114C2.84229 11.1772 1 13.1234 1 15.5C1 17.9853 3.01469 20 5.49995 20H17C20.3137 20 23 17.3137 23 14C23 10.9712 20.7558 8.46659 17.8395 8.05827ZM12.3201 8.26674C12.1347 8.11222 11.8653 8.11222 11.6799 8.26674L6.53047 12.5579C6.35084 12.7076 6.45669 13 6.69051 13H10V17.5C10 17.7761 10.2239 18 10.5 18H13.5C13.7761 18 14 17.7761 14 17.5V13H17.3095C17.5433 13 17.6492 12.7076 17.4695 12.5579L12.3201 8.26674Z"
            fill="currentColor"
          ></path>
        </svg>
      </el-upload>
      <div class="upload-options" v-if="percent && percent != 100 && !done">
        <el-link
          type="info"
          @click="PauseUpload"
          class="upload-icons"
          :underline="false"
          :icon="!Pause ? 'el-icon-video-pause' : 'el-icon-video-play'"
        ></el-link>
        <el-link
          type="info"
          class="upload-icons"
          :underline="false"
          @click="RefreshUpload"
          icon="el-icon-refresh"
        ></el-link>
        <el-link
          icon="el-icon-circle-close"
          class="upload-icons"
          @click="CancelUpload"
          :underline="false"
        ></el-link>
      </div>
    </div>

    <el-progress
      style="width:100%"
      v-if="percent && percent != 100 && !done"
      :percentage="percent"
    ></el-progress>
    <el-button
      v-if="fileList.length > 0 && !done"
      slot="trigger"
      size="small"
      :loading="loading"
      type="primary"
      @click="startUpload"
    >
      开始上传
    </el-button>
  </div>
</template>

<script>
import md5 from 'md5'
import axios from 'axios'
import { SHA512 } from 'crypto-js'
import { getAccessToken } from '@/utils/auth'
import { calculateSHA512 } from '@/utils/encrypt'
import {
  uploadVideoToCos,
  cancelUpload,
  restartUpload,
  deleteUploadFile,
  multipleAbort
} from '@/api/cos'

export default {
  data() {
    return {
      uploadUrl: '/api/v1/upload/videoUpload',
      headers: {
        'Content-Type': 'multipart/form-data',
        authorization: getAccessToken()
      },
      percent: 0,
      fileList: [],
      videoUrl: '',
      // 上传完成判断
      done: false,
      // 暂停标志位
      Pause: false,
      currentChunk: 0,
      total: 0,
      end_prefix: '',
      loading: false,
      currentFile: null,
      currentTaskId: null,
      isUpload: false
    }
  },
  computed: {
    chunkSize() {
      return 1024 * 1024
    },
    timemd5() {
      return md5(new Date().toString())
    }
  },
  methods: {
    onProgress(progress) {
      console.log('进度', progress)
      // 更新上传进度
      this.percent = progress.percent * 100
    },
    // 获取taskId
    onTaskReady(taskId) {
      this.currentTaskId = taskId
    },
    // 开始上传
    async startUpload() {
      this.done = false
      this.loading = true
      const file = this.$refs.upload.uploadFiles[0]
      // 格式校验
      const allowedExtensions = ['.mp4', '.mov', '.avi']
      const allowedMimeTypes = [
        'video/mp4',
        'video/quicktime',
        'video/x-msvideo'
      ]

      const fileExtension = file.name
        .substring(file.name.lastIndexOf('.'))
        .toLowerCase()
      const fileMimeType = file.type

      // 检查文件扩展名
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 MP4、MOV 或 AVI 格式的视频')
        this.fileList = []
        return
      }

      // 检查文件 MIME 类型
      if (!allowedMimeTypes.includes(fileMimeType)) {
        this.$message.error('只能上传 MP4、MOV 或 AVI 格式的视频')
        this.fileList = []

        return
      }
      // 如果文件存在
      if (file) {
        this.currentFile = file
        // cos存储
        uploadVideoToCos(file, file.name, this.onProgress, this.onTaskReady)
          .then(completeData => {
            // 上传完成后的处理逻辑
            this.done = true
            this.loading = false
            this.percent = 100
            this.videoUrl = 'http://' + completeData.Location
            this.isUpload = true
            this.$message.success('上传成功')
            // 存储url
            this.$store.commit('video/SETVIDEOURL', this.videoUrl)
          })
          .catch(error => {
            console.log(error)
          })
        // 本地存储
        // const { chunkSize, timemd5 } = this
        // const totalChunks = Math.ceil(file.size / this.chunkSize)
        // // 检查文件是否存在
        // const fileReader = new FileReader()
        // fileReader.onload = async () => {
        //   const arrayBuffer = fileReader.result;
        //   const uint8Array = new Uint8Array(arrayBuffer);
        //   // 格式转换
        //   const fileBlob = new Blob([arrayBuffer], { type: file.type });
        //   // 生成hash值
        //   const file_hash = await calculateSHA512(fileBlob);
        //   const datas = this.$qs.stringify({ file_hash })
        //   try {
        //     // 检查是否存在相同文件
        //     const res = await this.$API.video.CheckExist(datas)
        //     if (res && res.status == 200) {
        //       this.videoUrl = res.data.url
        //       console.log(res)
        //       this.$store.commit("video/SETVIDEOURL", this.videoUrl)
        //       // this.fileList = []
        //       this.done = true
        //       return
        //     }
        //   } catch (error) {
        //     this.$message.error("文件检查请求失败")
        //     return;
        //   }
        //   // 判断是否上传完了
        //   while (this.currentChunk < totalChunks && !this.done && !this.Pause) {
        //     const start = this.currentChunk * chunkSize;
        //     const end = Math.min(file.size, start + chunkSize);
        //     const chunk = file.slice(start, end);
        //     // 构建表单数据
        //     const formData = new FormData();
        //     this.total = file.size
        //     this.end_prefix = file.name.split(".").pop()
        //     formData.append('file', chunk);
        //     formData.append('start', start);
        //     formData.append('end', end);
        //     formData.append('total', this.total);
        //     formData.append('timemd5', timemd5);
        //     formData.append('end_prefix', this.end_prefix);

        //     // 发送分片请求
        //     try {
        //       await axios.post(this.uploadUrl, formData, {
        //         headers: {
        //           'Content-Type': 'multipart/form-data',
        //           'Authorization': getAccessToken()
        //         },
        //         onUploadProgress: progressEvent => {
        //           // 监听上传进度
        //           this.percent = Math.ceil((this.currentChunk / totalChunks) * 100);
        //           console.log('上传进度:', this.percent);
        //         }
        //       }).then(res => {
        //         console.log(res)
        //         if (res.data.data.done && this.currentChunk === totalChunks - 1) {
        //           this.done = true
        //           this.percent = 100
        //           this.videoUrl = res.data.data.url
        //           this.$store.commit("video/SETVIDEOURL", this.videoUrl)
        //           this.fileList = []
        //           this.$message.success("上传成功")
        //         }
        //       });

        //       this.currentChunk++;
        //     } catch (error) {
        //       this.$message.error("上传失败")
        //       this.done = false
        //       this.Pause = true
        //       console.error('分片上传失败:', error);
        //       return;
        //     }
        //   }
        // }
        // fileReader.readAsArrayBuffer(file);
      } else {
        console.warn('未选择文件')
      }
    },
    // 中断上传
    async InterruptUpload() {
      this.Pause = true
      const { total, end_prefix, timemd5 } = this
      let datas = new FormData()
      datas.append('total', total)
      datas.append('timemd5', timemd5)
      datas.append('end_prefix', end_prefix)
      try {
        const res = await this.$API.video.InterruptUploadVideo(datas)
        if (res.status == 200) {
          this.currentChunk = 0
          this.percent = 0
        }
      } catch (error) {
        this.$message.error('中断失败')
      }
    },
    // 取消上传
    async CancelUpload() {
      // cos取消上传

      await cancelUpload(this.currentTaskId)
      this.fileList = []
      this.done = true
      this.loading = false
      this.percent = 0
      this.$message.success('取消成功')
      // this.InterruptUpload().then(() => {

      //   // 清空列表
      //   this.fileList = []
      //   this.Pause = false
      // })
    },
    handleSuccess(response, file) {
      // 上传成功的回调函数
      // console.log('上传成功', response, file);
    },
    // 重新上传
    RefreshUpload() {
      // 中断后重新开始上传
      this.InterruptUpload().then(() => {
        this.Pause = false
        this.done = false
        this.currentChunk = 0
        this.startUpload()
      })
    },
    // 暂停上传功能
    async PauseUpload() {
      // cos存储
      this.Pause = !this.Pause
      // cos中断上传
      if (!this.Pause) {
        await restartUpload(this.currentTaskId)
      } else {
        await multipleAbort(this.currentTaskId)
      }
      // 本地存储
      // this.Pause = !this.Pause
      // if (!this.Pause) {
      //   this.startUpload()
      // }
    },
    handleError(error, file) {
      // 上传失败的回调函数
      console.error('上传失败', error, file)
    },
    beforeUpload(file) {
      this.fileList.push(file)
      this.currentChunk = 0
      this.done = false
      // 阻止自动上传
      return false
    },
    async handleRemove(file) {
      console.log(file)
      if (file.status == 'success') {
        // 如果存在url,就删除该文件
        if (this.videoUrl) {
          // cos存储删除
          const formData = new FormData()
          formData.append('url', this.videoUrl)
          // 检查是否关联
          const res = await this.$API.upload.DetectCosRemove(formData)
          if (res.status == 200) {
            // 删除cos存储文件
            const response = await deleteUploadFile(this.currentFile.name)
            if (res.status == 200 || res.status == 204) {
              this.fileList = []
              this.videoUrl = ''
            } else {
              return this.$message.error(res.msg)
            }
          } else if (res.status == 422) {
            this.fileList = []
            this.videoUrl = ''
          }
          // 本地存储删除
          // this.removeUploadFile(this.videoUrl)
        } else {
          // 清空文件列表
          this.fileList = []
        }
      }
      this.isUpload = false
    }
  }
}
</script>
<style scoped>
.upload-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.upload-content {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.upload-options {
  margin-right: 20px;
  margin-top: 20px;
}
.upload-icons {
  margin-left: 12px;
  font-size: 18px;
}
/* 更改图标样式 */
.BeforeUpload >>> .el-upload-list__item .el-icon-upload-success {
  background-image: url(@/assets/img/svg/circle.svg);
  background-repeat: no-repeat;
  background-size: 16px;
  background-position: center center;
  /* color: rgba(0, 0, 0, 0); */
}
.BeforeUpload >>> .el-icon-upload-success::before {
  /* content: ''; */
  font-size: 14px;
  visibility: hidden;
}
.UploadSuccess >>> .el-upload-list__item .el-icon-upload-success {
  background-image: url(@/assets/img/svg/circle-success.svg);
  background-repeat: no-repeat;
  background-size: 16px;
  background-position: center center;
  /* color: rgba(0, 0, 0, 0); */
}
.UploadSuccess >>> .el-icon-upload-success::before {
  /* content: ''; */
  font-size: 14px;
  visibility: hidden;
}
</style>